import { useInfiniteScroll } from "ahooks";
import { useRef } from "react";

import "@/index.css";

const PAGE_SIZE = 10;

const getList = (params: { pageNo: number; pageSize: number }) => {
  const { pageNo, pageSize } = params;
  const list = [];
  for (let i = pageNo; i < pageNo * pageSize + 1; i++) {
    list.push(i);
  }
  console.log("list ~ list:", list);
  return {
    list,
    total: 100,
  };
};

export const UseInfiniteScroll = () => {
  const ref = useRef<HTMLDivElement>(null);

  const handleList = async (nextPage: number | undefined) => {
    let pageNo = 1;
    if (nextPage) {
      pageNo = nextPage;
    }
    const params = {
      pageNo,
      pageSize: PAGE_SIZE,
    };
    const res = await getList(params);
    return {
      list: res?.list || [],
      nextPage: pageNo + 1,
      total: res?.total,
    };
  };

  const { data } = useInfiniteScroll(
    (d) => {
      return handleList(d?.nextPage);
    },
    {
      target: ref,
      isNoMore: (d) => {
        if (d) {
          return d.list.length >= d.total;
        } else {
          return true;
        }
      },
    }
  );
  return (
    <div
      ref={ref}
      className="h-48 w-24 overflow-auto bg-[#029CFD] justify-center"
    >
      {(data?.list || []).map((item) => (
        <div
          className="h-12 leading-12 w-20 text-center"
          style={{ border: "1px solid #ccc" }}
        >
          {item}
        </div>
      ))}
    </div>
  );
};
